package org.szy.core.common.controller;

import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.UploadedFile;
import org.szy.core.common.entity.R;
import org.szy.core.common.service.FileService;

import java.util.HashMap;
import java.util.Map;

/**
 * 公共上传文件控制类
 *
 * @author 孙志阳
 * @date 2023-02-22
 * @since 1.0.0
 **/
@Controller
@Mapping("/common/file")
public class FileController extends BaseController {

    @Inject
    private FileService fileService;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 上传后的地址
     */
    @Post
    @Mapping("/upload")
    public R<?> upload(UploadedFile file) {
        try {
            String fileUrl = fileService.uploadFile(file);
            Map<String, String> map = new HashMap<>(1);
            map.put("url", fileUrl);
            map.put("name", file.getName());
            return R.ok("上传文件成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("上传文件失败，原因：" + e.getMessage());
        }
    }


}
